<?php

namespace App\Admin\Controllers;

use App\Models\Carbarn;
use App\Models\Organization;
use App\Http\Controllers\Controller;
use App\Models\OrganizationType;
use App\Models\OrganizationUser;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Support\Facades\DB;

class OrganizationController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('BCS')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('详细')
            ->description('信息')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Create')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Organization);
        $grid->model()->with(['user', 'type', 'stations'])->withCount('carbarns')->orderBy('id', 'desc');

        $grid->id('Id');
        $grid->column('type.name', '合作商类型');
        $grid->name('合作商名称');
        $grid->address('合作商地址');
        $grid->company_tel('公司电话');
        $grid->column('created_time', '添加时间');
        $grid->column('carbarns_count', '洗车舱数量');
        $grid->column('门店数量')->display(function () {
            return $this->stations->unique('id')->count();
        });

        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->filter(function ($filters) {
            $filters->equal('org_type_id', '合作商类型')->select(OrganizationType::pluck('name', 'id'));
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Organization::with(['user', 'type', 'province', 'city', 'district'])->findOrFail($id));

        $show->id('Id');
        $show->user('负责人信息', function ($user) {
            $user->panel()->tools(function ($tools) {
                $tools->disableEdit();
                $tools->disableList();
                $tools->disableDelete();
            });
            $user->name('负责人姓名');
            $user->phone('负责人电话');
            $user->bank_name('开户行');
            $user->bank_account_name('开户人姓名');
            $user->bank_account_number('银行账号');
        });
        $show->org_type_id('类型')->as(function () {
            return $this->type->name;
        });
        $show->name('名称');
        $show->province_city_district('省-市-区')->as(function () {
            return sprintf('%s-%s-%s',  $this->province->name,  $this->city->name, $this->district->name);
        });
        $show->address('详细地址');
        $show->company_tel('公司电话');
        $show->created_time('Created time');
        $show->updated_time('Updated time');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Organization);

        $form->select('org_type_id', '合作商类型')->options(OrganizationType::pluck('name', 'id'))->rules('required');
        $form->text('name', '合作商名称')->rules('required');
        $form->distpicker(['province_code', 'city_code', 'district_code'])->attribute('data-value-type', 'code')->rules('required');
        $form->textarea('address', '详细地址')->rules('required');
        $form->text('company_tel', '公司电话')->rules('required');
        $form->text('user.name', '负责人姓名')->rules('required');
        $form->text('user.phone', '负责人电话')->rules('required');
        $form->text('user.bank_name', '开户银行');
        $form->text('user.bank_account_name', '开户人姓名');
        $form->text('user.bank_account_number', '银行账号');
        $form->password('user.password', '密码')->rules('required');
        $form->organization_station('carbarns', '关联的门店-洗车舱')->options(Carbarn::listBoxOptions());
//        $form->ignore(['related_carbarns']);

//        $form->listbox('carbarns', '关联的门店-洗车舱')
//            ->options(Carbarn::listBoxOptions())
//            ->settings(['nonSelectedListLabel' => '全部门店-洗车舱', 'selectedListLabel' => '已选择门店-洗车舱']);

//        $form->saving(function ($form) {
//            $user = $form->user;
//            $model = $form->model();
//            $userQuery = OrganizationUser::query()->where('phone', $user['phone']);
//            if ($model->org_uid) {
//                $userQuery->where('id', '!=', $model->org_uid);
//            }
//            $existsUser = $userQuery->first();
//            if ($existsUser) {
//                admin_error('错误', sprintf('手机: %s 已经被: %s 使用', $user['phone'], $existsUser->name));
//                return back()->withInput();
//            }
//            if ($user['password'] && optional($model->user)->password != $user['password']) {
//                $user['password'] = md5($user['password']);
//                $form->user = $user;
//            }
//
//        });
//
//        $form->saved(function ($form) {
//            $model = $form->model();
//            $carbarns = request('related_carbarns');
//            if (empty($carbarns)) {
//                $syncData = [];
//            } else {
//                foreach ($carbarns['cart_id'] as $key => $value) {
//                    $syncData[$value] = ['divided' => $carbarns['divided'][$key]];
//                }
//            }
//            $model->carbarns()->sync($syncData);
//        });
//
        $form->editing(function ($form) {
//            $model = $form->model();
//            $carbarns = $model->carbarns()->withPivot(['divided'])->get();
//
//            $model->setRelation('carbarns', $carbarns);

        });


        return $form;
    }

    public function store()
    {
        $data = request()->all();
        if ($validationMessages = $this->form()->validationMessages($data)) {
            return back()->withInput()->withErrors($validationMessages);
        }
        //验证手机是否可用
        $userQuery = OrganizationUser::query()->where('phone', $data['user']['phone']);
        $existsUser = $userQuery->first();
        if ($existsUser) {
            admin_error('错误', sprintf('手机: %s 已经被: %s 使用', $data['user']['phone'], $existsUser->name));
            return back()->withInput();
        }
        try {
            DB::transaction(function () use ($data) {
                //先创建用户
                $userData = $data['user'];
                $userData['password'] = md5($userData['password']);
                $user = OrganizationUser::create($userData);
                $data['org_uid'] = $user->id;
                //保存组织本身
                $organization = Organization::create($data);

                //保存关联的洗车舱
                $carbarns = $data['carbarns'];
                if ($carbarns) {
                    $syncData = [];
                    foreach ($carbarns['cart_id'] as $key => $value) {
                        if ($value) {
                            $dividValue = $carbarns['divided'][$key];
                            if (!is_numeric($dividValue) || $dividValue < 0 || $dividValue > 100) {
                                throw new \InvalidArgumentException("无效的分成比例：$dividValue, 有效值 0~100");
                            }
                            $syncData[$value] = ['divided' => $dividValue];
                        }
                    }
                    $organization->carbarns()->sync($syncData);
                }
                return api(RET_OK, "OK", $organization);
            });
        } catch (\Exception $exception) {
            return back()->withInput();
        }
    }

    public function update($id)
    {
        $data = request()->all();
        if ($validationMessages = $this->form()->validationMessages($data)) {
            return back()->withInput()->withErrors($validationMessages);
        }
        $organization = Organization::with('user')->findOrFail($id);
        //验证手机是否可用
        $userQuery = OrganizationUser::query()->where('phone', $data['user']['phone'])->where('id', '!=', $organization->user->id);
        $existsUser = $userQuery->first();
        if ($existsUser) {
            admin_error('错误', sprintf('手机: %s 已经被: %s 使用', $data['user']['phone'], $existsUser->name));
            return back()->withInput();
        }
        try {
            DB::transaction(function () use ($organization, $data) {
                //更新用户
                $userData = $data['user'];
                if ($userData['password'] != $organization->user->password) {
                    $userData['password'] = md5($userData['password']);
                }
                $organization->user->update($userData);

                //更新组织本身
                $organization->update($data);

                //保存关联的洗车舱
                $carbarns = $data['carbarns'];
                if ($carbarns) {
                    $syncData = [];
                    foreach ($carbarns['cart_id'] as $key => $value) {
                        if ($value) {
                            $dividValue = $carbarns['divided'][$key];
                            if (!is_numeric($dividValue) || $dividValue < 0 || $dividValue > 100) {
                                throw new \InvalidArgumentException("无效的分成比例：$dividValue, 有效值 0~100");
                            }
                            $syncData[$value] = ['divided' => $dividValue];
                        }
                    }
                    $organization->carbarns()->sync($syncData);
                }
            });
            return redirect()->route('organization.index');
        } catch (\Exception $exception) {
            admin_error($exception->getMessage());
            return back()->withInput();
        }
    }
}
